package cn.dapeng.rpc.common.handler;

import cn.dapeng.rpc.common.MyHeader;
import cn.dapeng.rpc.common.PackageMessage;
import cn.dapeng.rpc.common.RpcResponse;
import cn.dapeng.rpc.common.serial.JDKSerializeCoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerRequestHandlerV1 extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " closed ...... ");
        super.channelInactive(ctx);
        ctx.channel().close();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        PackageMessage requestPkm = (PackageMessage) msg;

        // 把消息传给客户端
        String ioThreadName = Thread.currentThread().getName();

        // 注意下面这两行，一个是在本线程执行，一个是在其他线程中执行
        ctx.executor().execute(() -> {
            //ctx.executor().parent().execute(() -> {

            try {
                String executeThreadName = Thread.currentThread().getName();

                RpcResponse response = new RpcResponse();
                response.setRequestId(requestPkm.getHeader().getRequestId());
                response.setResult("ioThread:" + ioThreadName + " execThread:" + executeThreadName + " args:" + requestPkm.getContent().getArgs()[0]);
                byte[] contentBody = JDKSerializeCoder.serial(response);

                MyHeader responseHeader = new MyHeader();
                responseHeader.setRequestId(requestPkm.getHeader().getRequestId());
                responseHeader.setFlag(0x14141424);
                responseHeader.setBodyLen(contentBody.length);

                byte[] headerBody = JDKSerializeCoder.serial(responseHeader);

                ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer(headerBody.length + contentBody.length);
                byteBuf.writeBytes(headerBody);
                byteBuf.writeBytes(contentBody);
                ctx.writeAndFlush(byteBuf);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

    }
}
